import React, { useRef, useState, useEffect } from 'react';

import { useParams } from 'react-router-dom';

import {
  ArrowLeftOutlined,
  PlusOutlined,
  ReloadOutlined,
  SettingOutlined,
  SwapOutlined,
} from '@ant-design/icons';

import { deviceGroupRemoveApi } from '@/api/deviceGroupApi';
import { type DeviceItem, deviceManagerListApi } from '@/api/deviceManagerApi';
import { equipmentProductListApi, type ProductItem } from '@/api/equipmentProductApi';
import { DeviceListStatus, getEnumItem, ProductNodeType } from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { TableLocalePresets } from '@/utils/tableUtils';

import AddDeviceDrawer from './AddDeviceModal';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 设备分组详情页
 */
const DeviceGroupDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { back, navigate } = useRouter();
  const actionRef = useRef<ActionType>(null);
  const [productOptions, setProductOptions] = useState<Array<{ label: string; value: string }>>([]);
  const [addDeviceModalVisible, setAddDeviceModalVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 获取产品列表
  const fetchProductList = async () => {
    try {
      const res = await equipmentProductListApi({
        current: 1,
        size: 1000, // 获取所有产品
      });
      if (res.success) {
        const options = res.data.records.map((product: ProductItem) => ({
          label: product.productName || '',
          value: product.productName || '',
        }));
        setProductOptions(options);
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
    }
  };

  // 初始化产品列表
  useEffect(() => {
    fetchProductList();
  }, []);

  // 获取分组内设备列表
  const fetchGroupDevices = async (params: Record<string, unknown>) => {
    try {
      const res = await deviceManagerListApi({
        ...params,
        groupId: id, // 根据分组ID筛选设备
      });
      const responseData = res.data;

      if (Array.isArray(responseData)) {
        return {
          success: res.success,
          data: responseData,
          total: responseData.length,
        };
      } else if (responseData && typeof responseData === 'object') {
        const listData = responseData as API.ListType<DeviceItem>;
        return {
          success: res.success,
          data: listData.records ?? [],
          total: listData.total ?? 0,
        };
      }

      return {
        success: res.success,
        data: [],
        total: 0,
      };
    } catch (error) {
      console.error('获取分组设备列表失败:', error);
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  // 添加设备到分组
  const handleAddDevice = () => {
    setAddDeviceModalVisible(true);
  };

  // 添加设备成功回调
  const handleAddDeviceSuccess = () => {
    // 刷新设备列表
    actionRef.current?.reload();
  };

  // 通用移除设备方法
  const removeDevices = async (deviceIds: number[], deviceName?: string) => {
    if (deviceIds.length === 0) {
      window.$message.warning('请选择要移除的设备');
      return;
    }
    try {
      const res = await deviceGroupRemoveApi({ deviceIds });

      if (res.success) {
        const message =
          deviceIds.length === 1
            ? `成功移除设备${deviceName ? ` "${deviceName}"` : ''}`
            : `成功移除 ${deviceIds.length} 台设备`;
        window.$message.success(message);

        // 刷新设备列表
        actionRef.current?.reload();
        // 清空选择状态
        setSelectedRowKeys([]);
      } else {
        window.$message.error(res.message || '移除设备失败');
      }
    } catch (error) {
      console.error('移除设备失败:', error);
      window.$message.error('移除设备失败，请重试');
    }
  };

  // 移除单个设备
  const handleRemoveDevice = async (deviceId: number | undefined, deviceName?: string) => {
    if (!deviceId) {
      window.$message.error('设备ID无效');
      return;
    }
    await removeDevices([deviceId], deviceName);
  };

  // 批量移除设备
  const handleBatchRemoveDevice = async (selectedRowKeys: React.Key[]) => {
    const deviceIds = selectedRowKeys.map(key => Number(key)).filter(id => !isNaN(id));
    await removeDevices(deviceIds);
  };

  // 获取设备状态标签
  const getStatusBadge = (status: number) => {
    const statusItem = getEnumItem(DeviceListStatus, String(status));
    return (
      <ABadge
        status={statusItem?.status as 'success' | 'processing' | 'default' | 'error' | 'warning'}
        text={statusItem?.label || '未知'}
      />
    );
  };

  // 获取节点类型标签
  const getNodeTypeTag = (nodeType: number) => {
    const nodeTypeItem = Object.values(ProductNodeType).find(item => item.value === nodeType);
    return nodeTypeItem ? nodeTypeItem.label : '未知';
  };

  // 表格列定义
  const columns: ProColumns<DeviceItem>[] = [
    {
      title: '设备code',
      dataIndex: 'code',
      key: 'code',
      width: 160,
      search: true,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 140,
      valueType: 'select',
      fieldProps: {
        options: productOptions,
        placeholder: '请选择产品',
        allowClear: true,
        showSearch: true,
        filterOption: (input: string, option?: { label: string; value: string }) =>
          option?.label?.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      search: false,
      render: (_, record) => getStatusBadge(record.status || 0),
    },
    {
      title: '节点类型',
      dataIndex: 'nodeType',
      key: 'nodeType',
      width: 100,
      search: false,
      render: (_, record) => <ATag color="blue">{getNodeTypeTag(record.nodeType || 0)}</ATag>,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '最近在线时间',
      dataIndex: 'latestOnlineTime',
      key: 'latestOnlineTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => navigate(`/device/list/detail/${record.id}`)}
          >
            详情
          </AButton>
          <AButton
            type="link"
            size="small"
            danger
            onClick={() => handleRemoveDevice(record.id, record.code)}
          >
            移除
          </AButton>
        </ASpace>
      ),
    },
  ];

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <ArrowLeftOutlined className="mx-4" onClick={back} />
        <div className="page-main-title">分组设备列表</div>
        <div className="page-sub-title">
          查看和管理当前分组下的所有设备，支持设备的添加、移除和详情查看
        </div>
      </div>

      <div className="page-content-box">
        <div className="page-content">
          {/* 设备列表卡片 */}
          <ACard>
            <PProTable<DeviceItem>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchGroupDevices}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton key="add" icon={<PlusOutlined />} type="primary" onClick={handleAddDevice}>
                  添加设备
                </AButton>,
                <AButton
                  key="batch-move"
                  icon={<SwapOutlined />}
                  danger
                  disabled={selectedRowKeys.length === 0}
                  onClick={() => handleBatchRemoveDevice(selectedRowKeys)}
                >
                  批量移除设备 {selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
                </AButton>,
              ]}
              rowSelection={{
                selectedRowKeys,
                onChange: newSelectedRowKeys => {
                  setSelectedRowKeys(newSelectedRowKeys);
                },
              }}
              locale={TableLocalePresets.product(actionRef)}
              tableAlertRender={false}
              tableAlertOptionRender={false}
            />
          </ACard>
        </div>
      </div>

      {/* 添加设备抽屉 */}
      <AddDeviceDrawer
        visible={addDeviceModalVisible}
        groupId={id || ''}
        onCancel={() => setAddDeviceModalVisible(false)}
        onSuccess={handleAddDeviceSuccess}
      />
    </div>
  );
};

export default DeviceGroupDetail;
